//
//  MineInfoModel.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/11.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import MappingAce
@objc
open class MineInfoModel: NSObject,GetMainPath {

    
    static let share = MineInfoModel()
    //在oc中这样写才能被调用
    @objc open class func sharedInstance() -> MineInfoModel
    {
        return MineInfoModel.share
    }
    /// 用户子信息
    var userInfModel: UserInfoModel?
    /// token
    var token: String?
    /// 是否登录
    var isLogin:Bool
    private override init() {
        self.isLogin = false
        super.init()
    }
}

extension MineInfoModel {
    
    /// 保存用户信息
    func saveUserData(userinfo:NSDictionary) {
        // 储存自定义对象
        let userDefaults = UserDefaults.standard
        // 实例对象转化成NSData
//        let jsonData:NSData = NSKeyedArchiver.archivedData(withRootObject: userinfo) as NSData
        var dict:NSMutableDictionary = NSMutableDictionary.init(dictionary: userinfo)
        if self.token != nil && self.token != "" {
            dict.setValue(self.token, forKey: "token")
        }
        userDefaults.set(dict, forKey: "user_info")
    }
    
    /// 读取用户信息
    func loadUserData() {
        // 储存自定义对象
        let userDefaults = UserDefaults.standard
        let myData =  userDefaults.object(forKey: "user_info")
        if myData == nil{
            let model = MineInfoModel.share
            model.token = ""
            return
        }
//        let myM =  NSKeyedUnarchiver.unarchiveObject(with: myData as! Data) as? NSDictionary
        var userModel = UserInfoModel(fromDic: myData as! [String : Any])
        let model = MineInfoModel.share

        model.userInfModel = userModel
        model.isLogin = true
        if userModel.token != "null" {
            model.token = userModel.token
        }else {
            model.token = ""
        }
    }
    
    /// 退出登录
    func exitLogin() {
        let model = MineInfoModel.share
        model.isLogin = false
        model.token = ""
        model.userInfModel = nil
        
        // 储存自定义对象
        let userDefaults = UserDefaults.standard
        // 实例对象转化成NSData
//        let jsonData:NSData = NSKeyedArchiver.archivedData(withRootObject: model as Any) as NSData
        userDefaults.removeObject(forKey: "user_info")
    }

    func hasLoginIn() -> Bool {

        let count = self.token?.count as Int?
        if let count = count {
            if count > 0 {
               return true
             }else{
               return false
            }
        }
         return false
    }
}
